// pages/mine/setting/recommend.js
var App = getApp();
Page({

  /**
   * 页面的初始数据
   */
  data: {
    recmdDiscont:'',
    codeImgSrc:'',
    allRecommend:0,
    hoverBox:false,
    inviteId:'',

    imgurl: '',
    canvasHidden: true,
    shareImgPath: '',
    screenWidth: '',       //设备屏幕宽度
    shareImgSrc: '',
    shareTempFilePath:'',
    targetSharePath:'' //canvas生成地址
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    let that = this;
    that.onSharePeople();
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function (res) {
    let that = this;
    return {
      title: '新人福利满10-5，在猫盒囤零食，超值！',
      path: '/pages/index/index?invite=' + that.data.inviteId,
      imageUrl: '/images/share.png',
      success: res => {
      },
      fail: res => {
      }
    }
  },
  //图片保存到手机
  save_img:function(){
    let that = this;
    that.saveImageToPhotosAlbum();

    wx.getSetting({
      success(res) {
        if (typeof(res.authSetting['scope.writePhotosAlbum']) == 'undefined' || res.authSetting['scope.writePhotosAlbum']) {//没有授权信息
          wx.authorize({
            scope: 'scope.writePhotosAlbum',
            success() {
              wx.saveImageToPhotosAlbum({
                filePath: that.data.targetSharePath,
                success(res) {
                  that.setData({
                    hoverBox: false
                  })
                  wx.showToast({
                    title: '保存成功',
                  })
                }
              })      
            }
          })
        } else if(!res.authSetting['scope.writePhotosAlbum']){//授权被拒
          wx.openSetting({
            success(res) {
              console.log(res.authSetting)

            }
          })
        }
      }
    })
    
  },  
  //back
  backLastPage: function () {
    wx.navigateBack({
      delta: 1
    })
  },
  // 显示弹窗
  showPayModal: function () {
    this.setData({
      hoverBox: !this.data.hoverBox
    })
  },

  //  获取用户推荐规则
  onShareMessage: function () {
    let that = this;
    wx.request({
      url: App.data.globalAPI + '/invite/user/getrule',
      data: {
        token: wx.getStorageSync('token')
      },
      method:'POST',
      header: {
        'content-type': 'application/x-www-form-urlencoded' // 默认值
      },
      success(res) {
        if (res.data.error == 0) {
          let quanMsg = res.data.data.coupon_name == undefined ? '' : res.data.data.coupon_name;
          let couponNum = res.data.data.coupon_num == undefined ? '' : res.data.data.coupon_num;
          that.setData({
            recmdDiscont: quanMsg + '劵' + couponNum +'张'
          })
        }else{
          wx.showToast({
            title: res.data.msg,
            icon:'none',
            duration:600
          })
        }
      }
    })
  },
  //  获取累计推荐人
  onSharePeople: function () {
    let that = this;
    wx.request({
      url: App.data.globalAPI + '/invite/user/getinfo',
      data: {
        token: wx.getStorageSync('token')
      },
      method: 'POST',
      header: {
        'content-type': 'application/x-www-form-urlencoded' // 默认值
      },
      success(res) {
        if (res.data.error == 0) {
          let info = res.data.data;
          let index = info.shareUrl.indexOf('invite_id=')+10;
          that.setData({
            codeImgSrc: info.qrcode,
            allRecommend: info.invite_total,
            inviteId: info.shareUrl.substring(index, info.shareUrl.length)
          })

          //生成图片信息
          wx.getImageInfo({
            src: that.data.codeImgSrc,
            success: function (res) {
              that.setData({
                shareImgPath: res.path
              });

              wx.getImageInfo({ //背景图片
                src: '../../../images/user_share_bg.png',
                success: function (res) {
                  that.setData({
                    shareImgSrc: '../../../' + res.path
                  });
                  //生成图片
                  that.saveImageToPhotosAlbum();
                }
              })
            }
          })
          

          //获取用户设备信息，屏幕宽度
          wx.getSystemInfo({
            success: res => {
              that.setData({
                screenWidth: res.screenWidth
              })
            }
          })
          
        } 
      },fail(){
        wx.showModal({
          title: '提示',
          content: '网络异常，请稍后重试！',
          showCancel: false,
          success(res) {
          }
        })
      }
    })
  },

  onReady: function () {
    var that = this;
    var context = wx.createCanvasContext('myCanvas', that);
    context.setStrokeStyle("#00ff00")
    context.setLineWidth(1)
    context.stroke()
    context.draw(false, that.getTempFilePath)
  },

  //获取临时路径
  getTempFilePath: function () {
    wx.canvasToTempFilePath({
      canvasId: 'myCanvas',
      success: (res) => {
        this.setData({
          shareTempFilePath: res.tempFilePath
        })
      }
    })
  },

  //保存至相册
  saveImageToPhotosAlbum: function () {
    var that = this; 
    var unit = that.data.screenWidth / 375
    //2. canvas绘制文字和图片
    const ctx = wx.createCanvasContext('myCanvas');
    var bgImgPath = that.data.shareImgSrc;

    //这里很重要，主要就是布局
    ctx.drawImage(bgImgPath, 0, 0, 375, 580);
    ctx.drawImage(that.data.shareImgPath, 145, 470, 80, 80);
    ctx.setFontSize(13)
    ctx.setFillStyle('#5e7436')
    ctx.stroke()
    ctx.draw(false, function () {
      // 3. canvas画布转成图片
      wx.canvasToTempFilePath({
        x: 0,
        y: 0,
        width: 375,
        height: 580,
        destWidth: 375,
        destHeight: 580,
        canvasId: 'myCanvas',
        success: function (res) {
          console.log(res);
          that.setData({
            canvasHidden:false,
            targetSharePath: res.tempFilePath
          })
          if (!res.tempFilePath) {
            wx.showModal({
              title: '提示',
              content: '图片绘制中，请稍后重试',
              showCancel: false
            })
          }
        },
        fail: function (res) {
          console.log(res)
        }
      })
    });
  },



})